package com.tedu.springboot2302.controller;


import com.tedu.springboot2302.entity.Article;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

//在writeArticle方法中将表单提交上来的标题和文章内容以及作者以Article对象形式序列化到目录articles
//        下文件名格式:标题.obj
//        保存后响应发表成功。如果标题或内容没有输入则响应发表失败页面。
@Controller
public class ArticleController {
    private static File userArticle;
    static{
        userArticle=new File("./articles");
        if (!userArticle.exists()){
            userArticle.mkdirs();
        }
    }
    @RequestMapping("/writeArticle")
    public void writeArticle(HttpServletRequest request, HttpServletResponse response){
        String title=request.getParameter("title");
        String author=request.getParameter("author");
        String content=request.getParameter("content");

        if (title==null||title.isEmpty()||
            author==null||author.isEmpty()||
            content==null||content.isEmpty()
        ){
            try {
                response.sendRedirect("/article_fail.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        Article article=new Article(title,author,content);
        File file=new File(userArticle,title+".obj");
        if (file.exists()){
            try {
                response.sendRedirect("/article_fail.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        try (
            FileOutputStream fos=new FileOutputStream(file);
            ObjectOutputStream oos=new ObjectOutputStream(fos);
                ){
           oos.writeObject(article);
           response.sendRedirect("/article_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
